/**
 * API服务模块 - 统一管理所有API调用
 * 提供认证、收藏、分类等API接口的封装
 */

class APIService {
    constructor() {
        this.apiBase = './api';
        this.token = localStorage.getItem('auth_token');
    }

    /**
     * 更新认证Token
     */
    setToken(token) {
        this.token = token;
        if (token) {
            localStorage.setItem('auth_token', token);
        } else {
            localStorage.removeItem('auth_token');
        }
    }

    /**
     * 获取认证Token
     */
    getToken() {
        return this.token || localStorage.getItem('auth_token');
    }

    /**
     * 通用API请求方法
     */
    async request(endpoint, method = 'GET', data = null) {
        const url = `${this.apiBase}/${endpoint}`;
        const token = this.getToken();
        
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            },
        };

        if (data && (method === 'POST' || method === 'PUT' || method === 'DELETE')) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);
            
            // 处理401未授权错误
            if (response.status === 401) {
                this.handleUnauthorized();
                throw new Error('未授权，请重新登录');
            }
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error('Response is not JSON');
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    /**
     * 处理未授权错误
     */
    handleUnauthorized() {
        this.setToken(null);
        localStorage.removeItem('auth_expires');
        localStorage.removeItem('remember_me');
        localStorage.removeItem('user_info');
        // 触发自定义事件通知应用
        window.dispatchEvent(new CustomEvent('unauthorized'));
    }

    // ==================== 认证相关API ====================

    /**
     * 用户注册
     */
    async register(username, email, password) {
        return await this.request('auth.php?action=register', 'POST', {
            username,
            email,
            password
        });
    }

    /**
     * 用户登录
     */
    async login(login, password, rememberMe = false) {
        const response = await this.request('auth.php?action=login', 'POST', {
            login,
            password,
            remember_me: rememberMe
        });
        
        // 登录成功后保存token
        if (response.success && response.data.session) {
            this.setToken(response.data.session.token);
            localStorage.setItem('auth_expires', response.data.session.expires_at);
            localStorage.setItem('remember_me', response.data.session.remember_me);
        }
        
        return response;
    }

    /**
     * 用户退出
     */
    async logout() {
        try {
            await this.request('auth.php?action=logout', 'POST');
        } finally {
            this.setToken(null);
            localStorage.removeItem('auth_expires');
            localStorage.removeItem('remember_me');
            localStorage.removeItem('user_info');
        }
    }

    /**
     * 验证Token
     */
    async verifyToken() {
        return await this.request('auth.php?action=verify', 'GET');
    }

    /**
     * 获取用户资料
     */
    async getProfile() {
        return await this.request('auth.php?action=profile', 'GET');
    }

    /**
     * 更新用户资料
     */
    async updateProfile(data) {
        return await this.request('auth.php?action=profile', 'PUT', data);
    }

    /**
     * 修改密码
     */
    async changePassword(currentPassword, newPassword) {
        return await this.request('auth.php?action=password', 'PUT', {
            current_password: currentPassword,
            new_password: newPassword
        });
    }

    // ==================== 收藏相关API ====================

    /**
     * 获取收藏列表
     */
    async getBookmarks(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const endpoint = queryString ? `bookmarks.php?${queryString}` : 'bookmarks.php';
        return await this.request(endpoint, 'GET');
    }

    /**
     * 获取单个收藏
     */
    async getBookmark(id) {
        return await this.request(`bookmarks.php?id=${id}`, 'GET');
    }

    /**
     * 创建收藏
     */
    async createBookmark(name, url, categoryId = null, description = '') {
        return await this.request('bookmarks.php', 'POST', {
            name,
            url,
            category_id: categoryId,
            description
        });
    }

    /**
     * 更新收藏
     */
    async updateBookmark(id, data) {
        return await this.request(`bookmarks.php?action=update&id=${id}`, 'POST', data);
    }

    /**
     * 移动收藏到分组
     */
    async moveBookmark(id, categoryId) {
        return await this.request(`bookmarks.php?action=move&id=${id}`, 'POST', {
            category_id: categoryId
        });
    }

    /**
     * 删除收藏
     */
    async deleteBookmark(id) {
        return await this.request(`bookmarks.php?action=delete&id=${id}`, 'POST', {
            action: 'delete',
            id: parseInt(id)
        });
    }

    /**
     * 搜索收藏
     */
    async searchBookmarks(query, page = 1, limit = 1000) {
        return await this.getBookmarks({
            search: query,
            page,
            limit
        });
    }

    // ==================== 分组相关API ====================

    /**
     * 获取分组列表
     */
    async getCategories() {
        return await this.request('categories.php', 'GET');
    }

    /**
     * 获取单个分组
     */
    async getCategory(id) {
        return await this.request(`categories.php?id=${id}`, 'GET');
    }

    /**
     * 创建分组
     */
    async createCategory(name, description = '', color = '#667eea', icon = 'fas fa-folder') {
        return await this.request('categories.php', 'POST', {
            name,
            description,
            color,
            icon
        });
    }

    /**
     * 更新分组
     */
    async updateCategory(id, data) {
        return await this.request('categories.php', 'POST', {
            action: 'update',
            id,
            ...data
        });
    }

    /**
     * 重排序分组
     */
    async reorderCategories(categories) {
        return await this.request('categories.php?action=reorder', 'POST', {
            categories
        });
    }

    // ==================== 导入API ====================

    /**
     * 上传并解析导入文件
     */
    async parseImportFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        
        const url = `${this.apiBase}/import.php?action=parse`;
        const token = this.getToken();
        
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Authorization': token ? `Bearer ${token}` : ''
            },
            body: formData
        });
        
        return await response.json();
    }

    /**
     * 执行批量导入
     */
    async importBookmarks(bookmarks, categoryId = null, skipDuplicates = true) {
        return await this.request('import.php?action=import', 'POST', {
            bookmarks,
            category_id: categoryId,
            skip_duplicates: skipDuplicates
        });
    }

    /**
     * 快速分析文件
     */
    async analyzeImportFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        
        const url = `${this.apiBase}/import.php?action=analyze`;
        const token = this.getToken();
        
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Authorization': token ? `Bearer ${token}` : ''
            },
            body: formData
        });
        
        return await response.json();
    }
}

// 创建全局单例
const apiService = new APIService();

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { APIService, apiService };
}

